import { ISocket,NetData} from "./WSInterface";
export class WSocket implements ISocket {
    private _ws:WebSocket=null;

    onConnected: (event: any) => void=null;
    onMessage: (msg: NetData) => void=null;
    onError: (event: any) => void=null;
    onClosed: (event: any) => void=null;

    connect(options: any){
        if(this._ws){
            if(this._ws.readyState===WebSocket.CONNECTING){
                console.log("websocket connecting");
                return false;
            }
        }
        let url=null;
        if(options.url){
            url=options.url;
        }
        else{
            let ip=options.ip;
            let port=options.port;
            let protocol=options.protocol;
            url=`${protocol}://${ip}:${port}`;
        }
        this._ws=new WebSocket(url);
        this._ws.binaryType=options.binaryType?options.binaryType:"arraybuffer";
        this._ws.onmessage=(event)=>{
            this.onMessage(event.data);
        };
        this._ws.onopen=this.onConnected;
        this._ws.onerror=this.onError;
        this._ws.onclose=this.onClosed;
        return true;
    };
    send(buffer: NetData){
        if(this._ws.readyState===WebSocket.OPEN){
            this._ws.send(buffer);
            return true;
        }
        return false;
    };

    close(code?: number, reason?: string){
        this._ws.close(code,reason);
    };
}
